<?php namespace Home\Controller;
use Hdphp\Controller\Controller;
use Common\Model\Category;
use Common\Model\Shop;
use Common\Model\Shop_list;
class CartController extends Controller{
	public function index(){
//		p($_SESSION);exit;
		if(isset($_SESSION['uid'])){
			$cateModel=new Category;
		$pid=$cateModel->where("cname='级别'")->pluck('cid');
//		p($pid);exit;
    	$cateData=$cateModel->where("pid!=0 and pid={$pid}")->get();
//		p($cateData);exit;
		View::with('cateData',$cateData);
		if(isset($_SESSION['cart']['goods'])){
			$data=$_SESSION['cart']['goods'];					
		}else{
			$data=[];
			$_SESSION['cart']['total']=0;
		}
//		p($_SESSION);
		if(isset($_SESSION['cart']['goods'])){
			view::with('shopnums',count($_SESSION['cart']['goods']));
			
		}else{
			view::with('shopnums',0);
		}

		
		View::with('data',$data);
		View::make();
		}else{
			View::error('请先登录',U('Member/login'));
		}
	}
    /**
     * 购物车添加
     */
    public function add(){
//  	组合属性id比数据库多一个逗号
    	$attrStr=Q('post.str');
//		去掉多的逗号
		$attrStr=substr($attrStr,0,strlen($attrStr)-1);
		$sid=Q('post.id');
		$shop_ListModel=new Shop_list;
		$slid=$shop_ListModel->where("combine='{$attrStr}' AND sid={$sid}")->pluck('slid');
    	$shopModel=new Shop;
		$market=$shopModel->where("sid={$sid}")->pluck('market');
        $data = [
            'id'        => Q('post.id'), // 商品 ID
            'name'      =>Q('post.name'),// 商品名称
            'num'       => 1, // 商品数量
            'price'     => Q('post.money'), // 商品价格
            'options' => [// 其他参数如价格、颜色、可以为数组或字符串
                    'attribute' => Q('post.spec'),
					'listgroup'=>Q('post.listgroup'),   
					'stock'=>Q('post.pid'),
					'market'=>$market,
					'slid'=> $slid     
                ]
            ];
        Cart::add($data);
		echo json_encode($data);exit;	
    }
//	删除购物车商品
	public function del(){
		if(isset($_GET['del'])){
			Cart::del(($_GET['del']));
		}
		View::success('删除成功','index');
	}
//  清空购物车
	public function dels(){
		unset($_SESSION['cart']);
		Cart::flush(); 
		View::success('购物车已清空',U('Index/index'));
	}
    public function edit(){
        $data=[
            'sid'=>Q('post.sid'),// 唯一 sid，添加购物车时自动生成
            'num'=>Q('post.num')
        ];
        Cart::update($data);
		$total=[];
//		全部商品总价
		$total['totals']=$_SESSION['cart']['total'];
//		一种商品总价
		$total['total']=$_SESSION['cart']['goods'][Q('post.sid')]['total'];			
		echo json_encode($total);
    }	
	
	//判断选择
	public function select_code(){		
		
		$total=[];
//		全部商品总价
//		p($_SESSION);
		$total['shopnums']=count($_SESSION['cart']['goods']);
		$total['totals']=$_SESSION['cart']['total'];

		
//		p($total);exit;
//		一种商品总价
//		$total['total']=$_SESSION['cart']['goods'][$session]['total'];			
		echo json_encode($total);

			


	}
}